const mongoose = require('mongoose')
const User = mongoose.model('User')
const api = require('../api')

// signup
exports.showSignup = async (ctx, next) => {
  await ctx.render('pages/signup', {
    title: '注册页面'
  })
}

exports.showSignin = async (ctx, next) => {
  await ctx.render('pages/signin', {
    title: '登录页面'
  })
}

exports.signup = async (ctx, next) => {
  const _user = ctx.request.body.user
  let user = await User.findOne({name: _user.name})

  if (user) {
    ctx.redirect('/signin')

    return next
  } else {
    user = new User(_user)
    await user.save()

    ctx.session.user = user

    ctx.redirect('/')
  }
}

// signin
exports.signin = async (ctx, next) => {
  const _user = ctx.request.body.user
  const name = _user.name
  const password = _user.password
  const user = await User.findOne({name: name})

  if (!user) {
    ctx.redirect('/signup')

    return next
  }

  const isMatch = await api.user.checkPassword(user.name, password)

  if (isMatch) {
    ctx.session.user = user

    ctx.redirect('/')
  } else {
    ctx.redirect('/signin')
  }
}

// logout
exports.logout = async (ctx, next) => {
  delete ctx.session.user
  // delete app.locals.user

  ctx.redirect('/')
}

// userlist page
exports.list = async (ctx, next) => {
  const users = await User
    .find({})
    .sort('meta.updateAt')

  await ctx.render('pages/userlist', {
    title: 'imooc 用户列表页',
    users: users
  })
}

// midware for user
exports.signinRequired = async (ctx, next) => {
  let user = ctx.session.user

  if (!user) {
    ctx.redirect('/signin')
  } else {
    await next()
  }
}

exports.adminRequired = async (ctx, next) => {
  let user = ctx.session.user

  if (user.role <= 10) {
    ctx.redirect('/signin')
  } else {
    await next()
  }
}
